package com.lcw.library.imagepicker.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.OpenableColumns;

import java.io.InputStream;

/**
 * 分区存储工具类
 * 
 * 用于处理Android 10+的分区存储适配
 * 提供文件访问和媒体查询的兼容性处理
 * 
 */
public class ScopedStorageUtil {

    /**
     * 判断当前设备是否启用了分区存储
     *
     * @return
     */
    public static boolean isScopedStorageEnabled() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
    }

    /**
     * 判断是否应该优先使用Uri而不是文件路径
     *
     * @param context
     * @return
     */
    public static boolean shouldUseUri(Context context) {
        return isScopedStorageEnabled() && Utils.getTargetSdkVersion(context) >= Build.VERSION_CODES.Q;
    }

    /**
     * 通过Uri获取文件名
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getFileNameFromUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }

        String fileName = null;
        ContentResolver contentResolver = context.getContentResolver();
        
        try (Cursor cursor = contentResolver.query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (nameIndex != -1) {
                    fileName = cursor.getString(nameIndex);
                }
            }
        } catch (Exception e) {
            // 静默处理异常，返回null表示无法获取文件名
        }

        return fileName;
    }

    /**
     * 通过Uri获取文件大小
     *
     * @param context
     * @param uri
     * @return
     */
    public static long getFileSizeFromUri(Context context, Uri uri) {
        if (uri == null) {
            return 0;
        }

        long size = 0;
        ContentResolver contentResolver = context.getContentResolver();
        
        try (Cursor cursor = contentResolver.query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                if (sizeIndex != -1) {
                    size = cursor.getLong(sizeIndex);
                }
            }
        } catch (Exception e) {
            // 静默处理异常，返回0表示无法获取文件大小
        }

        return size;
    }

    /**
     * 通过Uri获取MIME类型
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getMimeTypeFromUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }

        ContentResolver contentResolver = context.getContentResolver();
        return contentResolver.getType(uri);
    }

    /**
     * 检查Uri是否可以访问
     *
     * @param context
     * @param uri
     * @return
     */
    public static boolean isUriAccessible(Context context, Uri uri) {
        if (uri == null) {
            return false;
        }

        ContentResolver contentResolver = context.getContentResolver();
        try (InputStream inputStream = contentResolver.openInputStream(uri)) {
            return inputStream != null;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从文件路径构建MediaStore Uri（如果可能）
     *
     * @param context
     * @param filePath
     * @param isVideo 是否为视频文件
     * @return
     */
    public static Uri buildUriFromPath(Context context, String filePath, boolean isVideo) {
        if (filePath == null || filePath.isEmpty()) {
            return null;
        }

        ContentResolver contentResolver = context.getContentResolver();
        Uri baseUri = isVideo ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI : MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String dataColumn = isVideo ? MediaStore.Video.Media.DATA : MediaStore.Images.Media.DATA;
        String idColumn = isVideo ? MediaStore.Video.Media._ID : MediaStore.Images.Media._ID;

        try (Cursor cursor = contentResolver.query(
                baseUri,
                new String[]{idColumn},
                dataColumn + "=?",
                new String[]{filePath},
                null)) {
            
            if (cursor != null && cursor.moveToFirst()) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(idColumn));
                return Uri.withAppendedPath(baseUri, String.valueOf(id));
            }
        } catch (Exception e) {
            // 静默处理异常，返回null表示无法构建Uri
        }

        return null;
    }

    /**
     * 获取文件的真实路径（仅在允许的情况下）
     * 注意：在分区存储环境下，可能返回null
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getRealPathFromUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }

        // 在分区存储环境下，不建议使用文件路径
        if (shouldUseUri(context)) {
            return null;
        }

        ContentResolver contentResolver = context.getContentResolver();
        String[] projection = {MediaStore.MediaColumns.DATA};
        
        try (Cursor cursor = contentResolver.query(uri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                return cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            // 静默处理异常，返回null表示无法获取真实路径
        }

        return null;
    }

    /**
     * 检查是否为MediaStore Uri
     *
     * @param uri
     * @return
     */
    public static boolean isMediaStoreUri(Uri uri) {
        if (uri == null) {
            return false;
        }

        String authority = uri.getAuthority();
        return MediaStore.AUTHORITY.equals(authority);
    }

    /**
     * 检查是否为外部存储Uri
     *
     * @param uri
     * @return
     */
    public static boolean isExternalStorageUri(Uri uri) {
        if (uri == null) {
            return false;
        }

        String uriString = uri.toString();
        return uriString.startsWith(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString()) ||
               uriString.startsWith(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString());
    }
} 